<?php namespace Phpcmf\Controllers;

class Cart extends \Phpcmf\Home\Module {

    public function index() {

        $this->_module_init();

        if (IS_POST) {
            $ids = \Phpcmf\Service::L('Input')->get_post_ids();
            if (!$ids) {
                exit($this->_json(0, dr_lang('你还没有选择呢')));
            }
            $data = \Phpcmf\Service::M('Cart', 'store')->my_items($ids);
            if (!$data) {
                exit($this->_json(0, dr_lang('无可用商品')));
            }

            foreach ($data as $t) {
                list($a, $rid, $fid) = explode('-', $t['mid']);
                $field = $this->get_cache('table-field', $fid);
                if (!$field) {
                    exit($this->_json(0, dr_lang('支付字段[%s]不存在', $fid)));
                }
                $rt = \Phpcmf\Service::M('Pay')->get_pay_info($rid, $field, $t['quantity'], $t['sku_value']);
                if (isset($rt['code']) && !$rt['code']) {
                    exit($this->_msg(0, $rt['msg']));
                }
                \Phpcmf\Service::M('Cart', 'store')->update_cart($t['id'], $rt);
            }
            exit($this->_json(1, dr_lang('操作成功')));
        }

        $list = \Phpcmf\Service::M('Cart', 'store')->my_list($this->uid);

        \Phpcmf\Service::V()->assign([
            'list' => $list,
            'module' => $this->get_cache('module-'.SITE_ID),
            'my_list' => $list,
            'meta_title' => dr_lang('我的购物车').SITE_SEOJOIN.SITE_NAME,
            'meta_keywords' => $this->get_cache('site', SITE_ID, 'config', 'SITE_KEYWORDS'),
            'meta_description' => $this->get_cache('site', SITE_ID, 'config', 'SITE_DESCRIPTION')
        ]);
        \Phpcmf\Service::V()->display('cart.html');
    }

    // 购物车数量
    public function nums() {
        exit($this->_jsonp(1, 'ok', \Phpcmf\Service::M('Cart', 'store')->my_count($this->uid)));
    }

    // 购物车详情
    public function show() {

        if (!$this->uid) {
            exit($this->_jsonp(0, '没有登录', 0));
        }

        $list = \Phpcmf\Service::M('Cart', 'store')->my_list($this->uid);
        if (!$list) {
            exit($this->_jsonp(0, '没有商品', 0));
        }

        ob_start();
        \Phpcmf\Service::V()->assign('list', $list);
        \Phpcmf\Service::V()->display('api_show.html');
        $html = ob_get_contents();
        ob_clean();

        $this->_jsonp(1, $html);
    }

    // 删除购物车
    public function del() {

        if (!$this->uid) {
            exit($this->_jsonp(0, dr_lang('登录之后在操作')));
        }

        $id = (int)\Phpcmf\Service::L('Input')->get('id');
        if (!$id) {
            exit($this->_json(0, dr_lang('id参数不存在')));
        }

        exit($this->_jsonp(1, dr_lang('操作成功'), \Phpcmf\Service::M('Cart', 'store')->my_delete($this->uid, $id)));
    }

    // 更新购物车数量
    public function update() {

        if (!$this->uid) {
            exit($this->_jsonp(0, dr_lang('登录之后在操作')));
        }

        $id = (int)\Phpcmf\Service::L('Input')->get('id');
        $num = max(1, (int)\Phpcmf\Service::L('Input')->get('num'));
        if (!$id) {
            exit($this->_json(0, dr_lang('id参数不存在')));
        }

        $data = \Phpcmf\Service::M('Cart', 'store')->my_info($this->uid, $id);
        if (!$data) {
            exit($this->_jsonp(0, dr_lang('商品不存在')));
        }

        \Phpcmf\Service::M('Cart', 'store')->update_num($id, $num);

        exit($this->_jsonp(1, dr_lang('操作成功'), [
            'nums' => \Phpcmf\Service::M('Cart', 'store')->my_count($this->uid),
            'total' => number_format($data['price'] * $num, 2)
        ]));
    }

    // 加入购物车
    public function add() {

        if (!$this->uid) {
            exit($this->_json(0, dr_lang('登录之后在操作')));
        }

        $id = (int)\Phpcmf\Service::L('Input')->get('id');
        $fid = (int)\Phpcmf\Service::L('Input')->get('fid');

        if (!$id) {
            exit($this->_json(0, dr_lang('id参数不存在')));
        } elseif (!$fid) {
            exit($this->_json(0, dr_lang('字段fid参数不存在')));
        }

        $field = $this->get_cache('table-field', $fid);
        if (!$field) {
            exit($this->_json(0, dr_lang('支付字段[%s]不存在', $fid)));
        }

        // 获取付款价格
        $num = max(1, (int)\Phpcmf\Service::L('Input')->get('num'));
        $sku = dr_safe_replace(\Phpcmf\Service::L('Input')->get('sku'), 'undefined');
        $rt = \Phpcmf\Service::M('pay')->get_pay_info($id, $field, $num, $sku);
        if (isset($rt['code']) && !$rt['code']) {
            exit($this->_msg(0, $rt['msg']));
        }

        \Phpcmf\Service::M('cart', 'store')->add_cart($this->uid, $rt, $sku, $num);

        exit($this->_json(1, dr_lang('操作成功'), \Phpcmf\Service::M('cart', 'store')->my_count($this->uid)));
    }

    // 加入购物车并选择属性
    public function select() {

        if (!$this->uid) {
            exit($this->_json(0, dr_lang('登录之后在操作')));
        }

        $id = (int)\Phpcmf\Service::L('Input')->get('id');
        $fid = dr_safe_replace(\Phpcmf\Service::L('Input')->get('fid'));
        $mid = 'store';

        if (!$id) {
            exit($this->_json(0, dr_lang('id参数不存在')));
        } elseif (!$fid) {
            exit($this->_json(0, dr_lang('字段fid参数不存在')));
        }

        $module = \Phpcmf\Service::L('cache')->get('module-'.SITE_ID.'-'.$mid);
        if (!$module) {
            exit($this->_json(0, dr_lang('模块【%s】不存在', $mid)));
        }

        // 查询模块的数据
        $data = \Phpcmf\Service::M('cart', 'store')->get_module_row($mid, $id);
        if (!$data) {
            exit($this->_json(0, dr_lang('模块内容不存在')));
        } elseif (!isset($data[$fid])) {
            exit($this->_json(0, dr_lang('支付字段【%s】不存在', $fid)));
        } elseif (!isset($module['field'][$fid])) {
            exit($this->_json(0, dr_lang('支付字段【%s】未定义', $fid)));
        } elseif (!in_array($module['field'][$fid]['fieldtype'], ['Pay', 'Pays'])) {
            exit($this->_json(0, dr_lang('支付字段【%s】无效', $fid)));
        }

        $price = (float)$data[$fid];

        $_tmp = dr_string2array($data['thumb']);
        $thumb = is_array($_tmp) ? $_tmp['file'][0] : $data['thumb'];

        // 判断是否存在多属性商品
        $field = $module['field'][$fid];
        if ($module['field'][$fid]['fieldtype'] == 'Pays') {
            $sku = dr_string2array($data[$fid.'_sku']);
            if ($sku) {
                // 存在组合商品
                ob_start();
                \Phpcmf\Service::V()->assign([
                    'price' => $price,
                    'price_sku' => $sku,
                ]);
                \Phpcmf\Service::V()->display('cart_select.html');
                $html = ob_get_clean();
                exit($this->_json(2, $html, 'index.php?is_ajax=1&s=store&c=cart&m=add&id='.$id.'&fid='.$module['field'][$fid]['id'].'&thumb='.$thumb.'&url='.urlencode($data['url'])));
            }
        }

        // 表名-主键id-字段id-数量-sku
        $mid = SITE_ID.'_store' .'-'. $id .'-'. $field['id'] .'-1-null';

        $rt = [
            'mid' => $mid,
            'price' => $price,
            'url' => $data['url'],
            'title' => $data['title'],
            'thumb' => (string)$thumb,
            'sku_name' =>'',

        ];

        \Phpcmf\Service::M('cart', 'store')->add_cart($this->uid, $rt, '', 1);

        exit($this->_json(1, dr_lang('操作成功'), \Phpcmf\Service::M('cart', 'store')->my_count($this->uid)));
    }

    // 购物车点购买
    public function order() {

        if (!$this->uid) {
            exit($this->_json(0, '你还没有登录'));
        }

        $ids = \Phpcmf\Service::L('Input')->get_post_ids();
        if (!$ids) {
            exit($this->_json(0, dr_lang('购物车无商品')));
        }

        $cart = \Phpcmf\Service::M('Order', 'store')->my_cart_items($ids);
        if (!$cart) {
            exit($this->_json(0, dr_lang('购物车中商品无效')));
        }

        $cid = [];
        $mid = [];
        foreach ($cart as $t) {
            list($a, $rid, $fid) = explode('-', $t['mid']);
            list($s, $name) = explode('_', $a);
            $mid[$name] = $name;
            $field = $this->get_cache('table-field', $fid);
            if (!$field) {
                exit($this->_json(0, dr_lang('支付字段#%s不存在', $fid)));
            }
            $rt = \Phpcmf\Service::M('Pay')->get_pay_info($rid, $field, $t['quantity'], $t['sku_value']);
            if (isset($rt['code']) && !$rt['code']) {
                exit($this->_msg(0, $rt['msg']));
            } elseif (!$rt['quantity']) {
                exit($this->_msg(0, dr_lang('该商品【%s】已销售完', $rt['title'])));
            } elseif ($rt['quantity'] < $t['quantity']) {
                exit($this->_msg(0, dr_lang('该商品库存不足，商品剩余：%s', $rt['quantity'])));
            }
            $cid[] = $t['id'];
        }

        if (count($mid) > 2) {
            exit($this->_json(0, dr_lang('购物车中商品格式不正确')));
        }

        $cid = implode(',', $cid);
        $order = \Phpcmf\Service::M('Order', 'store')->my_order_cart_items($cid);
        if (!$order) {
            $rt = \Phpcmf\Service::M('Order', 'store')->add_my_order_cart($cid);
            if (!$rt['code']) {
                exit($this->_msg(0, $rt['msg']));
            }
            $order['id'] = $rt['code'];
        }

        exit($this->_json(
            1, dr_lang('正在为您下订单'), [
                'url' => dr_url('store/order/checkout', ['id' => $order['id']])
            ]
        ));
    }

}
